import httpInstance from "@/utils/http";
import { ElMessage } from "element-plus";
import { useTokenInfoStore } from '@/stores/login-Pinia'
import * as commonMethods from '@/apis/common'
import router from "@/router";
// 账号密码登录
export function passwordLogin(passwordLoginData){
    return httpInstance.post('/app-api/system/auth/login',passwordLoginData,{
        headers: {
            'Content-Type': 'application/json', // 或者根据实际需求使用其他 MIME 类型
          },
    })
}

export async function doPasswordLogin(passwordLoginData){
    passwordLoginData.userType = checkLoginUsertype("/app-api/")
    const result = commonMethods.AsyncCheckResultThenReturnData(await passwordLogin(passwordLoginData))
    console.log("result",result);
    // 判断有没有成功登录，登录成功后开启定时器主动更新token
    if(result){
        let tokenInfoStore = useTokenInfoStore()
        tokenInfoStore.$state = result
        // openRefreshTokenTimer()
        saveTokenInfoInLocalStorage()
        console.log("登陆成功");
        router.push("/home")
     }else{
        ElMessage.error('登录失败')
     }
}
// 获取用户类型
export function checkLoginUsertype(uri){
    if(uri.includes("/app-api/")){
        return 1
    }else if(uri.includes("/app-user-api/")){
        return 3
    }else if(uri.includes("/admin-api/")){
        return 2
    }else {
        ElMessage.error('用户类型错误')
    }
}
export function getRefreshToken(refreshTokenStr){
     return httpInstance.post('/app-api/system/auth/refresh-token',null,{
        params: {
            refreshToken: refreshTokenStr
        },//将refreshToken作为参数
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded' // 告知服务器正文是 JSON 格式
          }
    })   
}
// 检测token是否满足更新条件
export function validateCanGetRefreshToken(refreshToken,expiresTime){
            // 当refreshToken不等于空，代表用户已经登陆，并且时间再token过期时间前5s或者已经过期就发送请求刷新token
        if(refreshToken !== "" && expiresTime < Date.now() + 5000){
            return true
        }else{
            console.log('当前不满足更新token的条件',refreshToken,expiresTime);
            return false
        }
}

// 刷新token的定时器因为定时器开启后会一直请求，就算用户没有使用他也会一直发送请求，所以关闭定时器，让用户再每次发请求时再去验证token，如果更新token的token过期了就去重新登录，如果没有过期就更新token就行了

// export function openRefreshTokenTimer(){
//     let tokenInfostore = useTokenInfoStore()
//     setInterval(() => {
//         const commonResult = tokenInfostore.doAndCheckRefreshToken(tokenInfostore.getRefreshToken,tokenInfostore.getExpiresTime)
//         if(commonResult.code == 1){
//             tokenInfostore.$state = commonResult.data
//         }
//     }, 1000 * 60 * 13);
// }


// 获取登录用户的信息
export function getLoginUserBaseInfo(){
    return httpInstance.post('/app-api/system/user/profile/get',{
       headers: {
           'Content-Type': 'application/x-www-form-urlencoded' // 告知服务器正文是 JSON 格式
         }
   })   
}

// 将登录的tokenInfo存入LocalStorage
export function saveTokenInfoInLocalStorage(){
    let tokenInfoStore = useTokenInfoStore()
    localStorage.setItem("tokenInfo",JSON.stringify(tokenInfoStore.getTokenInfoStr()))
}

// 将登录的tokenInfo从LocalStorage删除
export function removeTokenInfoInLocalStorage(){
    localStorage.removeItem("tokenInfo")
}

// 操作退出登录逻辑
export async function doUserLogOut() {
    if(commonMethods.AsyncCheckResult( await userLogout())){
        console.log("退出登录成功");
        removeTokenInfoInLocalStorage()
        router.push("/")
    }
}

// 用户退出系统
export function userLogout(){
    return httpInstance.post('/app-api/system/auth/logout',{
       headers: {
           'Content-Type': 'application/x-www-form-urlencoded' // 告知服务器正文是 JSON 格式
         }
   })   
}